1. /* tools.h by K.Tsuru */
  2. // ver. 2.17
  3. /**************************************************************
  4. bisection method
  5. bisectn.cpp
  6. It solves an equation f(x) = 0 in the region of [a, b].
  7. **************************************************************/
  8. #ifndef TOOLS_H
  9. #include "tools.h"
  10. #endif // TOOLS_H
  11. double bisection(double a, double b, double tolerance, double (*f)(double)) {
  12. if (tolerance < 0) tolerance = 0;
  13. if (b < a) { double c = a; a = b; b = c; }
  14. double fa = f(a), fb = f(b);
  15. if (fa == 0) return a;
  16. if (fb == 0) return b;
  17. if (sameSign(fa, fb)) {
  18. fprintf(stderr, "f(a) * f(b) has positive sign in \"bisection()\"."); exit(-1);
  19. }
  20. for ( ; ; ) {
  21. double c = (a + b) / 2, fc = f(c);
  22. if (fc == 0) return c;
  23. if (c - a <= tolerance || b - c <= tolerance) break;
  24. if (sameSign(fc, fa)) { a = c; fa = fc; }
  25. else { b = c; fb = fc; }
  26. }
  27. return (a + b) / 2;
  28. }

bisectn.cpp : last modifiled at 2007/05/10 09:31:58(944 bytes)
created at 2016/04/11 11:17:20
The creation time of this html file is 2017/10/07 10:54:15 (Sat Oct 07 10:54:15 2017).